package model

import (
	"context"
	"errors"
	"net/http"
	"time"

	"github.com/uptrace/bun"
)

type DUser struct {
	bun.BaseModel `bun:"table:t_user,alias:u"`
	ID            int    `bun:"id,pk,autoincrement" json:"id"`
	Name          string `bun:"name" json:"name"`
	Account       string `bun:"account" json:"account"`
	DTime
}

type DTime struct {
	CreatedAt time.Time `bun:",nullzero,notnull" json:"created_at"`
	UpdatedAt time.Time `bun:",nullzero,notnull" json:"updated_at"`
}

var _ bun.BeforeAppendModelHook = (*DTime)(nil)

func (t *DTime) BeforeAppendModel(ctx context.Context, query bun.Query) error {
	switch query.(type) {
	case *bun.InsertQuery:
		t.CreatedAt = time.Now()
		t.UpdatedAt = time.Now()
	case *bun.UpdateQuery:
		t.UpdatedAt = time.Now()
	}
	return nil
}

type UserPayload struct {
	Name    string `json:"name"`
	Account string `json:"account"`
	// NoErrorBinder
}

func (u *UserPayload) Bind(r *http.Request) error {
	if u.Name == "" {
		return ErrOf(400, errors.New("用户名不能为空"))
	}
	if u.Account == "" {
		return ErrOf(400, errors.New("用户账号不能为空"))
	}
	return nil
}

type NoErrorBinder struct{}

func (b *NoErrorBinder) Bind(r *http.Request) error {
	return nil
}

type PageParam struct {
	PageSize int
	PageNo   int
}

// 分页Offset
func (p *PageParam) Offset() int {
	return (p.PageNo - 1) * p.PageSize
}

// 分页Limit
func (p *PageParam) Limit() int {
	return p.PageSize
}

// 分页结果
type PageResult[T any] struct {
	Size   int `json:"pageSize"`
	Number int `json:"page"`
	Total  int `json:"totalRows"`
	Rows   []T `json:"rows"`
}

func PageOf[T any](p PageParam, data []T, total int) PageResult[T] {
	if data == nil {
		data = make([]T, 0)
	}

	var r = PageResult[T]{}
	r.Size = p.PageSize
	r.Number = p.PageNo
	r.Total = total
	r.Rows = data
	return r
}
